package com.micro.gateway.filter;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.codec.HttpMessageReader;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.reactive.function.server.HandlerStrategies;
import org.springframework.web.reactive.function.server.ServerRequest;

import java.util.List;

/**
 * @Author Reyna.chen
 * @Date 2022/1/6 19:06
 * @Version 1.0
 * @Description:密码解密工具类自定义路由器
 */
@Slf4j
@RequiredArgsConstructor
public class PasswordDecoderFilter extends AbstractGatewayFilterFactory {

    private static final List<HttpMessageReader<?>> messageReaders = HandlerStrategies.withDefaults().messageReaders();

    private static final String PASSWORD = "password";

    private static final String KEY_ALGORITHM = "AES";

    // private final GatewayConfigProperties gatewayConfig;

    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            // 1. 不是登录请求，直接向下执行
//            if (!StrUtil.containsAnyIgnoreCase(request.getURI().getPath(), SecurityConstants.OAUTH_TOKEN_URL)) {
//                return chain.filter(exchange);
//            }

            // 2. 刷新token类型，直接向下执行
//            String grantType = request.getQueryParams().getFirst("grant_type");
//            if (StrUtil.equals(SecurityConstants.REFRESH_TOKEN, grantType)) {
//                return chain.filter(exchange);
//            }

            // 3. 前端加密密文解密逻辑
            Class<String> inClass = String.class;
            Class<String> outClass = String.class;
            ServerRequest serverRequest = ServerRequest.create(exchange, messageReaders);
            return chain.filter(exchange);

            // 4. 解密生成新的报文
//            Mono<?> modifiedBody = serverRequest.bodyToMono(inClass).flatMap(decryptAES());
//
//            BodyInserter bodyInserter = BodyInserters.fromPublisher(modifiedBody, outClass);
//            HttpHeaders headers = new HttpHeaders();
//            headers.putAll(exchange.getRequest().getHeaders());
//            headers.remove(HttpHeaders.CONTENT_LENGTH);
//
//            headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
//            CachedBodyOutputMessage outputMessage = new CachedBodyOutputMessage(exchange, headers);
//            return bodyInserter.insert(outputMessage, new BodyInserterContext()).then(Mono.defer(() -> {
//                ServerHttpRequest decorator = decorate(exchange, headers, outputMessage);
//                return chain.filter(exchange.mutate().request(decorator).build());
//            }));
        };
    }
}
